<template>
  <div class="statistics-container">
    <!-- 添加 Loading 组件 -->
    <Loading v-if="isLoading" />

    <div class="nav-header">
      <router-link to="/main/bill-list" class="back-button">
        <span class="icon">◀</span>
        <span>返回</span>
      </router-link>
      <h2 class="page-title">账单统计</h2>
    </div>

    <div class="month-selector">
      <button
          class="month-button prev"
          @click="changeMonth(-1)"
      >
        ◀ 上月
      </button>
      <span class="current-month">{{ formatMonth(currentMonth) }}</span>
      <button
          class="month-button next"
          @click="changeMonth(1)"
          :disabled="isCurrentMonthOrFuture"
      >
        下月 ▶
      </button>
    </div>

    <!-- 本月结余卡片 -->
    <div class="balance-card card">
      <h3 class="card-title">本月结余</h3>
      <div class="balance-amount gradient-text">{{ formatAmount(monthlyOverview.monthlyBalance) }}</div>
      <div class="balance-details">
        <div class="detail-item">
          <span class="label">收入</span>
          <span class="amount income">{{ formatAmount(monthlyOverview.incomeTotal, true) }}</span>
        </div>
        <div class="detail-item">
          <span class="label">支出</span>
          <span class="amount expense">{{ formatAmount(monthlyOverview.expenseTotal, true) }}</span>
        </div>
      </div>
    </div>

    <!-- 支出类目排行卡片 -->
    <div class="category-ranking-card card">
      <h3 class="card-title">支出类目排行</h3>
      <div v-if="categoryRanking.length === 0" class="no-data">
        暂无支出数据
      </div>
      <div v-else class="ranking-list">
        <div 
          v-for="(category, index) in displayedCategoryRanking" 
          :key="category.name" 
          class="ranking-item clickable"
          @click="selectCategory(category.name)"
        >
          <div class="rank-number">{{ index + 1 }}</div>
          <div class="category-icon">{{ getCategoryIcon(category.name) }}</div>
          <div class="category-info">
            <div class="category-name">{{ category.name }}</div>
            <div class="progress-bar">
              <div class="progress" :style="{ width: `${category.percentage}%`, background: 'var(--primary-gradient)' }"></div>
            </div>
          </div>
          <div class="category-amount">{{ formatAmount(category.amount, true) }}</div>
          <div class="arrow-icon">▶</div>
        </div>
      </div>
      <div v-if="categoryRanking.length > 3" class="view-more" @click="toggleCategoryRanking">
        {{ showAllCategories ? '收起' : '查看更多' }}
      </div>
    </div>

    <!-- 支出明细排行卡片 -->
    <div class="expense-details-card card">
      <h3 class="card-title">支出明细排行</h3>
      <div v-if="expenseRanking.length === 0" class="no-data">
        暂无支出数据
      </div>
      <div v-else class="expense-list">
        <div v-for="(expense, index) in displayedExpenseRanking" :key="index" class="expense-item">
          <div class="rank-number">{{ index + 1 }}</div>
          <div class="expense-info">
            <div class="expense-name">{{ expense.remark || expense.category }}</div>
            <div class="expense-date">{{ expense.date }}</div>
          </div>
          <div class="expense-amount">{{ formatAmount(expense.amount, true) }}</div>
        </div>
      </div>
      <div v-if="expenseRanking.length > 3" class="view-more" @click="toggleExpenseRanking">
        {{ showAllExpenses ? '收起' : '查看更多' }}
      </div>
    </div>

    <!-- 类别详情弹窗 -->
    <Modal 
      :visible="showCategoryModal" 
      :title="`${selectedCategory} 支出明细`"
      @confirm="closeCategoryModal" 
      @cancel="closeCategoryModal"
    >
      <div class="modal-category-header">
        <div class="modal-category-icon">{{ getCategoryIcon(selectedCategory || '') }}</div>
        <div class="modal-category-total">
          <div class="label">类别总计</div>
          <div class="total-amount">{{ formatAmount(categoryDetails?.total || 0, true) }}</div>
        </div>
      </div>
      
      <div class="modal-expense-list" v-if="categoryDetails">
        <div v-if="categoryDetails.expenses.length === 0" class="no-data">
          暂无该类别支出数据
        </div>
        <div v-else>
          <div v-for="(expense, index) in categoryDetails.expenses" :key="index" class="modal-expense-item">
            <div class="expense-info">
              <div class="expense-name">{{ expense.remark || '无备注' }}</div>
              <div class="expense-date">{{ expense.date }}</div>
            </div>
            <div class="expense-amount">{{ formatAmount(expense.amount, true) }}</div>
          </div>
        </div>
      </div>
    </Modal>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue';
import Loading from "../../components/Loading/Loading.vue";
import Modal from "../../components/Modal/Modal.vue";
import {
  getMonthlyStatistics,
  getCategoryRanking,
  getExpenseRanking,
  getAllCategories,
  getCategoryDetails,
  MonthlyOverview,
  CategoryRanking,
  ExpenseDetail,
  Category,
  CategoryDetails
} from '../../api/modules/statistics.api';

// 数据加载状态
const isLoading = ref(false);

// 当前选中的月份（格式：YYYY-MM）
const currentMonth = ref(new Date().toISOString().substring(0, 7));

// 统计数据
const monthlyOverview = ref<MonthlyOverview>({
  incomeTotal: 0,
  expenseTotal: 0,
  monthlyBalance: 0
});

const categoryRanking = ref<CategoryRanking[]>([]);
const expenseRanking = ref<ExpenseDetail[]>([]);
const categories = ref<Category[]>([]);
const categoryDetails = ref<CategoryDetails | null>(null);

// 状态控制
const showAllCategories = ref(false);
const showAllExpenses = ref(false);
const selectedCategory = ref<string | null>(null);
const showCategoryModal = ref(false);

// 计算当前月份是否为当前月或未来月
const isCurrentMonthOrFuture = computed(() => {
  const now = new Date();
  const currentMonthStr = now.toISOString().substring(0, 7);
  return currentMonth.value >= currentMonthStr;
});

// 加载所有统计数据
async function loadAllStatistics() {
  isLoading.value = true;
  try {
    // 并行请求所有数据
    const [
      monthlyData,
      categoryRankingData,
      expenseRankingData,
      categoriesData
    ] = await Promise.all([
      getMonthlyStatistics(currentMonth.value),
      getCategoryRanking(currentMonth.value),
      getExpenseRanking(currentMonth.value),
      getAllCategories(currentMonth.value)
    ]);

    monthlyOverview.value = monthlyData;
    categoryRanking.value = categoryRankingData;
    expenseRanking.value = expenseRankingData;
    categories.value = categoriesData;
  } catch (error) {
    console.error('加载统计数据失败:', error);
  } finally {
    isLoading.value = false;
  }
}

// 加载类别详情
async function loadCategoryDetails(category: string) {
  isLoading.value = true;
  try {
    categoryDetails.value = await getCategoryDetails(category, currentMonth.value);
  } catch (error) {
    console.error(`加载类别 ${category} 详情失败:`, error);
    categoryDetails.value = null;
  } finally {
    isLoading.value = false;
  }
}

// 选择类别并打开详情弹窗
function selectCategory(category: string) {
  selectedCategory.value = category;
  showCategoryModal.value = true;
  loadCategoryDetails(category);
}

// 关闭类别详情弹窗
function closeCategoryModal() {
  showCategoryModal.value = false;
}

// 切换月份
function changeMonth(delta: number) {
  const date = new Date(currentMonth.value + '-01');
  date.setMonth(date.getMonth() + delta);
  currentMonth.value = date.toISOString().substring(0, 7);
}

// 格式化月份显示
function formatMonth(monthStr: string) {
  const date = new Date(monthStr + '-01');
  return `${date.getFullYear()}年${date.getMonth() + 1}月`;
}

// 计算属性: 显示的类别排行
const displayedCategoryRanking = computed(() => {
  return showAllCategories.value ? categoryRanking.value : categoryRanking.value.slice(0, 3);
});

// 计算属性: 显示的支出排行
const displayedExpenseRanking = computed(() => {
  return showAllExpenses.value ? expenseRanking.value : expenseRanking.value.slice(0, 3);
});

// 切换类别排行显示
function toggleCategoryRanking() {
  showAllCategories.value = !showAllCategories.value;
}

// 切换支出排行显示
function toggleExpenseRanking() {
  showAllExpenses.value = !showAllExpenses.value;
}

// 根据类别名称获取图标
function getCategoryIcon(categoryName: string) {
  const category = categories.value.find(c => c.name === categoryName);
  return category ? category.icon : '📊';
}

// 统一金额格式化
function formatAmount(amount: number, absolute = false) {
  const value = absolute ? Math.abs(amount) : amount;
  return value >= 0
      ? `¥${value.toFixed(2)}`
      : `-¥${Math.abs(value).toFixed(2)}`;
}

// 监听月份变化，重新加载数据
watch(currentMonth, () => {
  loadAllStatistics();
});

// 组件挂载时加载数据
onMounted(() => {
  loadAllStatistics();
});
</script>

<style scoped>
.statistics-container {
  max-width: 800px;
  margin: 20px auto;
  padding: 0 15px;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.nav-header {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-bottom: 5px;
}

.month-selector {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 10px;
}

.month-button {
  background: var(--primary-gradient);
  color: white;
  border: none;
  border-radius: 6px;
  padding: 8px 12px;
  cursor: pointer;
  font-weight: 500;
  transition: opacity 0.3s;
}

.month-button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.current-month {
  font-weight: 600;
  font-size: 16px;
}

.back-button {
  display: flex;
  align-items: center;
  gap: 5px;
  padding: 8px 12px;
  background: var(--primary-gradient);
  color: white;
  border-radius: 6px;
  text-decoration: none;
  font-weight: 500;
  transition: background 0.3s;
}

.back-button:hover {
  background: var(--primary-gradient-hover);
}

.page-title {
  margin: 0;
  color: var(--text-color);
  flex-grow: 1;
}

.card {
  background: #fff;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border: 1px solid var(--border-color);
}

.card-title {
  font-size: 18px;
  margin-top: 0;
  margin-bottom: 16px;
  color: var(--text-color);
  position: relative;
}

.card-title::after {
  content: '';
  position: absolute;
  left: 0;
  bottom: -8px;
  height: 3px;
  width: 50px;
  background: var(--primary-gradient);
  border-radius: 3px;
}

/* 余额卡片样式 */
.balance-amount {
  font-size: 32px;
  font-weight: bold;
  margin: 20px 0;
  text-align: center;
}

.balance-details {
  display: flex;
  justify-content: space-around;
  margin-top: 16px;
}

.detail-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.label {
  font-size: 14px;
  color: #666;
}

.amount {
  font-size: 18px;
  font-weight: 600;
  margin-top: 5px;
}

.amount.income {
  color: #28a745;
}

.amount.expense {
  color: #dc3545;
}

/* 排行卡片通用样式 */
.ranking-item, .expense-item {
  display: flex;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
}

.ranking-item.clickable {
  cursor: pointer;
  transition: background-color 0.2s;
  padding: 12px;
  margin: 0 -12px;
  border-radius: 8px;
}

.ranking-item.clickable:hover {
  background-color: #f8f9fa;
}

.arrow-icon {
  margin-left: 8px;
  color: #999;
  font-size: 12px;
}

.rank-number {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  background: var(--primary-gradient);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  margin-right: 10px;
}

.category-icon {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  margin-right: 10px;
  background: #f0f2f5;
}

.category-info, .expense-info {
  flex-grow: 1;
}

.category-name, .expense-name {
  font-weight: 500;
  margin-bottom: 5px;
}

.expense-date {
  font-size: 12px;
  color: #999;
}

.progress-bar {
  height: 5px;
  background: #f0f0f0;
  border-radius: 3px;
  overflow: hidden;
  margin-top: 5px;
}

.progress {
  height: 100%;
  border-radius: 3px;
}

.category-amount, .expense-amount {
  font-weight: 600;
  text-align: right;
  min-width: 80px;
}

.view-more {
  text-align: center;
  color: var(--primary-color);
  padding: 10px 0;
  cursor: pointer;
  font-weight: 500;
  margin-top: 10px;
}

.view-more:hover {
  text-decoration: underline;
}

/* 弹窗内容样式 */
.modal-category-header {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 16px;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  border-radius: 8px;
  margin-bottom: 16px;
}

.modal-category-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32px;
  background: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.modal-category-total {
  flex: 1;
}

.modal-category-total .label {
  font-size: 14px;
  color: #666;
  margin-bottom: 5px;
}

.modal-expense-list {
  max-height: 400px;
  overflow-y: auto;
}

.modal-expense-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px;
  border-bottom: 1px solid #f0f0f0;
  background: #fafafa;
  margin-bottom: 8px;
  border-radius: 6px;
}

.modal-expense-item:last-child {
  border-bottom: none;
}

.total-amount {
  font-size: 18px;
  font-weight: 600;
  color: var(--primary-color);
}

.no-data {
  text-align: center;
  color: #999;
  padding: 20px 0;
  font-size: 14px;
}

@media (max-width: 576px) {
  .balance-amount {
    font-size: 28px;
  }

  .amount {
    font-size: 16px;
  }

  .category-container {
    gap: 10px;
  }

  .category-btn .category-icon {
    width: 40px;
    height: 40px;
    font-size: 20px;
  }
}
</style>